<template>
  <view class="pages">
    <u-sticky
      class="sticky_c"
      offsetTop="0"
      :style="{ backgroundColor: scrollBgc ? '#F6F2FB' : '#F6F2FB' }"
    >
      <h-line :height="statusHeight + 20" bgColor="#F6F2FB"></h-line>
      <view class="navbar">
        <view class="nav_b">
          <u-icon name="arrow-left" size="22" color="#333" @click="goBack"></u-icon>
        </view>
        <view class="page_title">产检详情</view>
        <view class="nav_right">
          <u-button
            v-if="false"
            type="primary"
            @click="saveEualuation"
            shape="circle"
            text="保存"
            class="custom-style"
          ></u-button>
        </view>
      </view>
    </u-sticky>
    <view class="weeks">
      <text class="antenatal_num">{{ reportShowData.name }}</text>
      <view class="antenatal_main">
        <view>必查项目：</view>
        <view v-if="reportShowData.type == 0" class="antenatal_main_item">
          <text v-for="(i, n) in reportShowData.bcxm_cate" :key="n">{{ i }}</text>
        </view>
        <view v-else class="antenatal_main_item">
          <text v-for="(i, n) in reportShowData.user_cate" :key="n">{{ i.name }}</text>
        </view>
      </view>
    </view>
    <view class="prenatal_time">
      <view class="prenatal_time_box">
        <view class="time_title">产检时间</view>
        <view class="time_box">
          <view class="week_time">
            <text>{{ revealVal || reportShowData?.check_date }}</text>
            <text>{{ weeksValue || reportShowData?.week_day }}</text>
          </view>
          <!-- <u-icon name="arrow-right" size="18" color="#333333"></u-icon> -->
        </view>
      </view>
    </view>
    <view class="report_box">
      <view class="report_title">报告单</view>
      <view class="img_listBox">
        <view class="img_list" v-for="(item, index) in fileList" :key="index">
          <image :src="item" mode="aspectFill" @click="previewImg(fileList, index)"></image>
        </view>
      </view>
    </view>
    <view class="save_info" v-if="false">
      <view class="redio_box">
        <u-checkbox-group :usedAlone="true">
          <up-checkbox
            :customStyle="{ marginBottom: '8px' }"
            :checked="ifChecked"
            shape="circle"
            activeColor="#A28AFF"
            @change="checkboxChange"
          >
          </up-checkbox>
        </u-checkbox-group>
      </view>
      <view class="info_text">
        <view>请您知悉检查报告为个人敏感信息，并同意上传存储检查报告，</view>
        <view>咪婴伴侣不会将检查报告用作其它用途。</view>
      </view>
    </view>
    <!-- 提示 -->
    <h-modal
      :show="bindShow"
      titlea="是否保存编辑上传内容"
      leftBtn="取消"
      rightBtn="保存"
      @clear="clearEdit"
      @bind="saveEditFn"
    ></h-modal>
    <!-- 时间选择 -->
    <u-datetime-picker
      :formatter="formatter"
      title="请选取实际产检日期"
      :show="showDatePicker"
      v-model="newDate"
      mode="datetime"
      :maxDate="maxDate"
      @close="showDatePicker = false"
      @cancel="showDatePicker = false"
      :closeOnClickOverlay="true"
      @confirm="onDateConfirm"
    ></u-datetime-picker>
    <!-- 上传 -->
    <h-authpup
      ref="authpup"
      :h="userStore.statusHeight"
      type="top"
      @changeAuth="changeAuth"
      permissionID="CAMERA"
    ></h-authpup>
  </view>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { useMemberStore } from '@/stores'
import { onLoad, onPageScroll, onShow } from '@dcloudio/uni-app'
import { navigateBack, navigateTo, formatDate, showToast, redirectTo } from '@/utils'
import { uploadApi } from '@/utils/upLoad'
import { getReportDetail, getPrenatalExamination, saveEditApi } from '@/api/pregnancy/index'
const userStore = useMemberStore()
const scrollBgc = ref()
const bindShow = ref(false)
const statusHeight = ref()
//文本展示
const reportShowData = ref({})
//sahngc
const authpup = ref(null)
// 图片列表
const fileList = ref([])
//回显图片列表
const echoImgList = ref([])
//回显参数
const reportId = ref(0)
const reportDataInfo = ref({})
const showDatePicker = ref(false)
//周几
const newDate = ref(Date.now())
const maxDate = ref(Date.now())
//展示时间
const revealVal = ref('')
const weeksValue = ref('')
const formatter = (type, value) => {
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  return value
}

//参数
const params = ref({
  id: 0,
  date: '',
  report: [],
  type: 0,
})
const propsuid = ref()
onLoad((options) => {
  propsuid.value = options?.uid
  reportId.value = options?.id
  params.value.id = options?.id
})
onShow(() => {
  uni.getSystemInfo({
    success: (e) => {
      statusHeight.value = e?.statusBarHeight * 2
    },
  })
  getPrenatalList()
  getReportDetailList()
})
//回显
async function getReportDetailList() {
  const res = await getReportDetail({ id: reportId.value, uid: propsuid.value })
  if (res.code == 200) {
    reportDataInfo.value = res.data.data[0]
    params.value.date = res.data.data[0].date
    if (res.data.data[0].cj_report.length > 0) {
      ifChecked.value = true
      echoImgList.value = res.data.data[0].cj_report.map((item) => {
        return item
      })
      fileList.value = echoImgList.value || []
    }
  }
}
function toCheckReport() {
  showDatePicker.value = true
}
//获取列表
async function getPrenatalList() {
  const res = await getPrenatalExamination({ uid: propsuid.value })
  if (res.code == 200) {
    res.data.data.forEach((item) => {
      if (item.id == reportId.value) {
        reportShowData.value = item
        params.value.date = item.date
      }
    })
  }
}
function openAuth() {
  nextTick(() => {
    authpup.value.open()
  })
}
function changeAuth() {
  uni.chooseImage({
    count: 16 - fileList.value?.length, //默认9
    sizeType: ['compressed'],
    success: async (e) => {
      select(e)
    },
  })
}
async function select(evt) {
  var list = evt.tempFilePaths
  var num = 5 * 1024 * 1024
  for (var i in list) {
    if (list[i].size > num) {
      var a = Number(i) + 1
      uni.showToast({
        title: '第' + a + '张图片上传失败',
        icon: 'none',
        duration: 2000,
      })
      continue
    }
    uni.showLoading({
      title: '上传中...',
    })
    const res = await uploadApi(list[i])
    fileList.value.push(res)
    uni.hideLoading()
  }
}
// 新增图片
// const afterRead = async (event) => {
//   // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
//   console.log(event.file)
//   let lists = [].concat(event.file)
//   let fileListLen = fileList.value.length
//   lists.map((item) => {
//     fileList.value.push({
//       ...item,
//       status: 'uploading',
//       message: '上传中',
//     })
//   })
//   for (let i = 0; i < lists.length; i++) {
//     const result = await uploadApi(lists[i].url)
//     let item = fileList.value[fileListLen]
//     fileList.value.splice(fileListLen, 1, {
//       ...item,
//       status: 'success',
//       message: '',
//       url: result,
//     })
//     fileListLen++
//   }
// }
// 删除图片
// const deletePic = (event) => {
//   fileList.value.splice(event.index, 1)
// }
// 删除图片
const toDelete = (index) => {
  fileList.value.splice(index, 1)
}
//保存草稿
async function saveEditFn() {
  params.value.type = 2
  params.value.report = fileList.value.map((item) => item)
  const res = await saveEditApi({ uid: propsuid.value, ...params.value })
  if (res.code == 200) {
    uni.showToast({
      title: '保存成功！',
      icon: 'none',
    })
    redirectTo(`/pregnancys/index/time-table/record-test?type=2`)
  } else {
    showToast(res.msg)
  }
}
//保存报告
async function saveEualuation() {
  if (fileList.value.length == 0) {
    showToast('请上传报告单')
    return
  } else if (!params.value) {
    showToast('请选择时间')
    return
  } else if (!ifChecked.value) {
    showToast('请您勾选个人信息提示')
    return
  } else {
    params.value.type = 1
    params.value.report = fileList.value.map((item) => item)
    const res = await saveEditApi(params.value)
    if (res.code == 200) {
      uni.showToast({
        title: '保存成功！',
        icon: 'none',
      })
      navigateBack()
    } else {
      showToast(res.msg)
    }
  }
}
const ifChecked = ref(false)
function checkboxChange() {
  ifChecked.value = true
}
//时间选择
function onDateConfirm(e) {
  const weekselect = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  showDatePicker.value = false
  newDate.value = e.value
  revealVal.value = formatDate(e.value, 'YYYY-MM-DD')
  let week = new Date(revealVal.value).getDay()
  weeksValue.value = weekselect[week]
  params.value.date = `${revealVal.value} ${weeksValue.value}`
  console.log(params.value.date)
}
// 返回
function goBack() {
  navigateBack()
}
//取消
function clearEdit() {
  bindShow.value = false
  navigateBack()
}
//预览
function previewImg(list, index) {
  uni.previewImage({
    urls: list,
    current: index,
    fail: (err) => {
      console.log(err)
    },
  })
}
</script>

<style lang="scss" scoped>
.pages {
  width: 750rpx;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f6f6f6;
  font-family: PingFang-SC-Bold, PingFang-SC;
  padding-bottom: 30rpx;
  .weeks {
    width: 702rpx;
    height: 179rpx;
    background: #ffffff;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    padding: 30rpx 26rpx;
    margin-top: 30rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .antenatal_num {
      font-weight: 600;
      font-size: 32rpx;
      color: #333333;
    }
    .text_mian {
      width: 650rpx;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      font-size: 26rpx;
      color: #333333;
      margin-top: 20rpx;
    }
    .antenatal_main {
      display: flex;
      font-size: 26rpx;
      color: #333333;
      margin: 20rpx 0;
      .antenatal_main_item {
        width: 500rpx;
        display: -webkit-box;
        font-size: 26rpx;
        color: #333333;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        text {
          margin-right: 10rpx;
        }
      }
    }
  }
  .prenatal_time {
    width: 702rpx;
    height: 110rpx;
    background: #ffffff;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    padding: 30rpx 26rpx;
    margin: 30rpx 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .prenatal_time_box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .time_title {
        font-weight: 600;
        font-size: 26rpx;
        color: #333333;
      }
      .time_box {
        display: flex;
        .week_time {
          font-size: 26rpx;
          color: #333333;
          margin-right: 10rpx;
          text {
            margin-left: 16rpx;
          }
        }
      }
    }
  }
  .report_box {
    background: #ffffff;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    padding: 30rpx 26rpx;
    margin: 0 24rpx;
    .report_title {
      font-weight: 600;
      font-size: 26rpx;
      color: #333333;
    }
    .img_listBox {
      width: 643rpx;
      display: flex;
      flex-wrap: wrap;

      .img_list {
        display: flex;
        flex-wrap: wrap;
        justify-content: start;

        image {
          margin-right: 20rpx;
          width: 201rpx;
          height: 209rpx;
          display: block;
          border-radius: 16rpx;
        }
      }
      .img_list:nth-child(3n) image {
        margin-right: 0;
      }
    }
  }
  .save_info {
    display: flex;
    align-items: flex-start;
    margin-top: 10rpx;
    .info_text {
      font-size: 18rpx;
      color: #999999;
      width: 504rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-top: 10rpx;
    }
  }
}
.custom-style {
  width: 102rpx;
  height: 46rpx;
  background: #a28aff;
  border-radius: 69rpx 69rpx 69rpx 69rpx;
}
.slot-btn {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  width: 135rpx;
  height: 135rpx;
  background: #f6f6f6;
  border-radius: 13rpx 13rpx 13rpx 13rpx;
  margin-bottom: 20rpx;
  padding-top: 20rpx;
}

.slot-btn__hover {
  background-color: rgb(235, 236, 238);
}
.sticky_c {
  top: 0 !important;
  background: #f6f2fb;
  background-size: 100%;
  .navbar {
    padding: 0 24rpx;
    width: 100vw;
    height: 100rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    box-sizing: border-box;
    .page_title {
      font-family: PingFang SC, PingFang SC;
      font-weight: 600;
      font-size: 36rpx;
      color: #333333;
      margin-left: 11rpx;
      margin-right: 20rpx;
      line-height: 100rpx;
      text-align: center;
      flex: 1;
    }
    .nav_b {
      width: 100rpx;
      height: 32rpx;
      padding: 30rpx 0;
    }
    .nav_right {
      width: 102rpx;
      height: 46rpx;
      display: flex;
      align-items: center;
      .right_item {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-left: 20rpx;
        image {
          width: 30rpx;
          height: 30rpx;
          margin-bottom: 4rpx;
        }
        text {
          font-size: 16rpx;
          color: #000000;
        }
      }
    }
  }
  .round_edge {
    width: 750rpx;
    height: 40rpx;
    background: #f6f6f6;
    border-radius: 25rpx 25rpx 0rpx 0rpx;
  }
}
</style>
